package com.cn.yz.service.sysauthority.manager;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import com.cn.yz.common.constant.CList;
import com.cn.yz.common.manager.TokenManager;
import com.cn.yz.common.utils.CookieUtils;
import com.cn.yz.common.utils.JsonUtils;
import com.cn.yz.service.sysauthority.config.SystemConfigBean;

@EnableConfigurationProperties({SystemConfigBean.class})
@Component
public class DefaultTokenManager implements TokenManager {
	
	private static final Logger LOG = LoggerFactory.getLogger(DefaultTokenManager.class);
	
	@Autowired
	SystemConfigBean systemConfigBean;
	
	@Autowired
	StringRedisTemplate stringRedisTemplate;
	
	@Resource(name="stringRedisTemplate")
	ValueOperations<String,Object> valOpsStr;

	@Override
	public void createToken(HttpServletResponse response,Map<String, Object> map) {
		LOG.info("DefaultTokenManager.createToken");
		String token = getRandomString(systemConfigBean.getTokenLength());
		valOpsStr.set(token, JsonUtils.toJsonString(map));
		LOG.info("DefaultTokenManager.createToken   token---->" + token);
		try {
			CookieUtils.addCookie(CList.DEFAULT_TOKEN_NAME, token, response, systemConfigBean.getCookieAge());
		} catch (Exception e) {
			LOG.error("Cookie设置失败---->"+e.getMessage());
		}
	}

	@Override
	public boolean checkToken(HttpServletRequest request, String token) {
		// TODO Auto-generated method stub
		return false;
	}

	//获取指定位数的随机字符串(包含小写字母、大写字母、数字,0<length)
	private String getRandomString(int length) {
	    //随机字符串的随机字符库
	    String KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	    StringBuffer sb = new StringBuffer();
	    int len = KeyString.length();
	    for (int i = 0; i < length; i++) {
	       sb.append(KeyString.charAt((int) Math.round(Math.random() * (len - 1))));
	    }
	    return sb.toString();
	}
}
